package xml;

import model.*;

import model.Direction;
import com.thoughtworks.xstream.converters.*;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class TileConverter implements Converter{

	//XML Tags
	private static final String EXIT_XML_TAG = "exit";
	private static final String VISITED_XML_TAG = "visited";
	private static final String Y_COORD_XML_TAG = "y";
	private static final String X_COORD_XML_TAG = "x";

	@Override
	public void marshal(Object source, HierarchicalStreamWriter writer,
			MarshallingContext context) {
		Tile tile = (Tile) source;
		
		writer.startNode(X_COORD_XML_TAG);
		writer.setValue(((Integer)tile.getXCoord()).toString());
		writer.endNode();
		
		writer.startNode(Y_COORD_XML_TAG);
		writer.setValue(((Integer)tile.getYCoord()).toString());
		writer.endNode();
		
		writer.startNode(VISITED_XML_TAG);
		context.convertAnother((Boolean) !tile.hasDot());
		writer.endNode();
		
		for(Direction dir : Direction.values())
			if (tile.getExit(dir) != null) {
				writer.startNode(EXIT_XML_TAG);
				writer.addAttribute("dir", dir.toString());
				writer.startNode(X_COORD_XML_TAG);
				writer.setValue(((Integer)tile.getExit(dir).getXCoord()).toString());
				writer.endNode();
				
				writer.startNode(Y_COORD_XML_TAG);
				writer.setValue(((Integer)tile.getExit(dir).getYCoord()).toString());
				writer.endNode();
				writer.endNode();
			}
			
		
	}

	@Override
	public Object unmarshal(HierarchicalStreamReader reader,
			UnmarshallingContext context) {
		return null;
	}

	/**
	 * Checks to see if the class attempting to use this converter is
	 * a Tile
	 */
	@SuppressWarnings("unchecked")
	@Override
	public boolean canConvert(Class type) {
		return type.equals(Tile.class);
	}
	

}
